Regular expressions have their own syntax that is understood by regular expression engines. Those engines will throw an exception at runtime if they are given a regular expression that does not conform to that syntax.

To avoid syntax errors, special characters should be escaped with backslashes when they are intended to be matched literally and references to capturing groups should use the correctly spelled name or number of the group.

Negative lookahead and negative lookbehind groups cannot be combined with RegexOptions.NonBacktracking. Such combination would throw an exception during runtime.

Noncompliant Code Example

public void DoSomething(string input)
{
    var regex = new Regex("[A");                // Noncompliant
    var match = Regex.Match(input, "[A");       // Noncompliant
    var matches = Regex.Matches(input, "[A");   // Noncompliant
    var replace = Regex.Replace(input, "[A", "replacement");    // Noncompliant
    var split = Regex.Split(input, "[A");       // Noncompliant
    if(Regex.IsMatch(input, "[A"))              // Noncompliant
    {
    }
    var negativeLookahead = new Regex("a(?!b)", RegexOptions.NonBacktracking);      // Noncompliant
    var negativeLookbehind = new Regex("(?<!a)b", RegexOptions.NonBacktracking);    // Noncompliant
}

Compliant Solution

public void DoSomething(string input)
{
    var regex = new Regex("[A-Z]");
    var match = Regex.Match(input, "[A-Z]");
    var matches = Regex.Matches(input, "[A-Z]");
    var replace = Regex.Replace(input, "[A-Z]", "replacement");
    var split = Regex.Split(input, "[A-Z]");
    if(Regex.IsMatch(input, "[A-Z]"))
    {
    }
    var negativeLookahead = new Regex("a(?!b)");
    var negativeLookbehind = new Regex("(?<!a)b");
}